package game.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import common.model.po.GCreature;
import common.model.request.base.PaginationRequest;
import common.model.response.base.Result;
import game.mapper.GCreatureMapper;
import game.model.converter.GCreatureConverter;
import game.model.request.SaveCreatureRequest;
import game.model.request.SearchCreatureRequest;
import game.model.vo.SearchCreatureVo;
import game.service.GCreatureService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

/**
 * 服务实现类
 *
 * @author 米泽鹏
 * @since 2023-11-28 下午 06:19
 */
@Service
public class GCreatureServiceImpl extends ServiceImpl<GCreatureMapper, GCreature> implements GCreatureService {

	@Resource
	private GCreatureMapper mapper;

	@Override
	public Page<SearchCreatureVo> searchCreatureByPage(PaginationRequest<SearchCreatureRequest, GCreature> paginationRequest) {
		return mapper.pageSearchCreature(paginationRequest.buildPage(), paginationRequest.getParams());
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public Result<?> saveCreature(SaveCreatureRequest request) {
		GCreature creature = GCreatureConverter.saveRequestToPo(request);
		// 找出最大伤害
		List<Integer> damage = creature.getDamage();
		if (CollUtil.isNotEmpty(damage)) {
			damage.stream().mapToInt(Integer::intValue).max().ifPresent(creature::setMaxDamage);
		} else {
			creature.setMaxDamage(null);
		}
		if (creature.getId() == null) {
			save(creature);
		} else {
			updateById(creature);
		}
		return Result.success();
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public Result<?> deleteCreature(Long id) {
		// 删除物品
		removeById(id);
		return Result.success();
	}

}
